package com.itHaipeng.utils;

import com.mchange.v2.c3p0.DataSources;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;

/**
 * 连接的工具类，用于从数据源中获取一个链接并且和一个线程进行绑定
 *
 * */
@Service(value = "connectionUtil")
public class ConnectionUtil {
    //先new 一个ThreadLocal对象
    private ThreadLocal<Connection> connectionThreadLocal=new ThreadLocal<>();
    @Autowired
    private DataSource dataSource;
    //提供一个获取当前线程的链接
    /**
     * 获取当前线程上的链接
     * @return
     * */
    public Connection getThreadConnection() {
        try {
            //先从ThreadLocal上获取
            Connection connection = connectionThreadLocal.get();
            //2判断当前线程上是否有链接，
            if (connection == null) {
                //3:从数据源中获取一个链接，并且和线程进行绑定，存入ThreadLocal中
                connection = dataSource.getConnection();
                //4：把connection存入ThreadLocal中
                connectionThreadLocal.set(connection);
            }
            //5:返回当前上的线程链接
            return connection;
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
    /**
     * 把连接和线程解绑
     * */
    public void removeConnection(){
        connectionThreadLocal.remove();
    }
}
